<template>
    <el-dialog
            :before-close="closeDialog" :title="isEdit ? '修改员工' : '新增员工'" :visible.sync="localFormVisible"
            width="35%" top="20px" :close-on-click-modal="false"
    >
        <el-form ref="formRef" :model="formData" :rules="rules">
            <el-form-item v-if="isEdit" :label-width="formLabelWidth" label="员工编号" prop="empId">
                <el-input v-model="formData.empId" autocomplete="off" readonly ></el-input>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="员工姓名" prop="empName">
                <el-input v-model="formData.empName" autocomplete="off" ></el-input>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="用户名" prop="username">
                <el-input v-model="formData.username" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="员工角色" prop="roleId">
                <el-select v-model="formData.roleId">
                    <el-option
                            v-for="role in roleList" :key="role.roleId"
                            :label="role.role" :value="role.roleId"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="所属部门" prop="deptId">
                <el-select v-model="formData.deptId">
                    <el-option
                            v-for="dept in deptList" :key="dept.deptId"
                            :label="dept.deptName" :value="dept.deptId"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="性别" prop="genderId">
                <el-radio-group v-model="formData.genderId">
                    <el-radio :label=1>男</el-radio>
                    <el-radio :label=2>女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="员工号码" prop="phone">
                <el-input v-model="formData.phone" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="入职日期" prop="hiredate">
                <!-- format：日期框显示的格式，用户看到的格式
                     value-format：值的格式            -->
                <el-date-picker
                        v-model="formData.hiredate"
                        format="yyyy 年 MM 月 dd 日"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :picker-options="pickerOption"
                >
                </el-date-picker>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="closeDialog">关闭</el-button>
            <el-button type="primary" @click="saveForm">保存</el-button>
        </div>
    </el-dialog>
</template>

<script>
export default {
    name: "EmpForm",
    data() {
        return {
            //表单元素宽度
            formLabelWidth: '120px',
            localFormVisible: this.formVisible,
            //限制入职日期
            pickerOption: {
                disabledDate(time) {
                    return time.getTime() > Date.now()
                }
            },
            // 表单验证规则
            rules: {
                empName: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符之间', trigger: 'blur' },
                    { validator: this.validateUsername, trigger: 'change' }/*验证用户名重复*/
                ],
                roleId: [{ required: true, message: '请选择员工角色', trigger: 'change' }],
                deptId: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
                genderId: [{ required: true, message: '请选择性别', trigger: 'change' }],
                phone: [
                    { required: false, message: '请输入员工号码', trigger: 'blur' },
                    { pattern: /^[0-9]{10}$/, message: '员工号码必须为10位数字', trigger: 'blur' }
                ],
                hiredate: [
                    { required: true, message: '请选择入职日期', trigger: 'change' },
                ],
            },
        }
    },
    methods: {
        closeDialog() {
            this.localFormVisible = false;
            //通知父组件修改formVisible的值为false
            this.$emit('update:formVisible', false)
        },
        saveForm() {
            this.$refs['formRef'].validate((valid) => {
                if (valid) {
                    //调用父组件的保存方法
                    this.$emit('submitForm', this.formData)
                } else {
                    return false;
                }
            });
        },

        //验证用户名是否重复
        async validateUsername(rule, value, callback) {
                if (!value) {
                    callback(new Error('请输入用户名'));
                } else {
                    try {
                        if (this.isEdit){
                            const  originalEmp = (await this.$http.post('/getEmpById/' + this.formData.empId)).data
                            if (originalEmp.username !==value){
                                const response = await this.$http.post('/checkUsername/' + value);
                                if (response.data) {
                                    callback(new Error('用户名已存在'));
                                } else {
                                    callback();
                                }
                            }
                        }else {
                            const response = await this.$http.post('/checkUsername/' + value);
                            if (response.data) {
                                callback(new Error('用户名已存在'));
                            } else {
                                callback();
                            }
                        }
                    } catch (error) {
                        console.error('验证用户名时出错:', error);
                        callback(new Error('验证用户名时出错，请稍后再试'));
                    }
                }
        },
    },
    props: {
        isEdit: {
            type: Boolean,
            default: false
        },
        formVisible: {
            type: Boolean,
            default: false
        },
        formData: Object,
        deptList: Array,
        roleList: Array
    },
    watch: {
        formVisible(newVal) {
            this.localFormVisible = newVal; // 当 `prop` 改变时，更新本地变量
            if (newVal) {
                if (this.$refs['formRef']) {
                    this.$refs['formRef'].resetFields(); // 当弹框打开时重置表单
                }
            }
        }
    },
}
</script>

<style scoped>

</style>